//
//  ShopingCartViewController.m
//  GoBigMarket
//
//  Created by legend on 16/8/3.
//  Copyright © 2016年 legend. All rights reserved.
#import "ShopingCartViewController.h"
#import "SectionHeaderTableView.h"
#import "MyProductsTool.h"
#import "ConfirmOderViewController.h"
#import "CommodityViewController.h"
#import "WelcomViewController.h"
@interface ShopingCartViewController ()<UITableViewDelegate,UITableViewDataSource,BWYShoppingCarDelegate,UIAlertViewDelegate>{
    NSMutableArray * _shoppingCarDataArray;
    UITableView * _shoppingCarTableView;
    UIButton * allButton;
    UILabel * moneyLable;
    float priceNumber;
    UIImageView * _backGrundImageView;
    UIButton * balanceButton;
    UILabel *sendMoney;
    
}
@property (nonatomic, strong) SectionHeaderTableView *header;
@property (nonatomic, strong) NSMutableArray *selectedIndexPathArr;
@property (nonatomic, strong) NSNumber *fillPrice;
@property (nonatomic, strong) UIView *viewBa;
@end

@implementation ShopingCartViewController

#pragma mark - VC加载完成
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = XNColor(240, 240, 240, 1);
    _shoppingCarDataArray = [[NSMutableArray alloc]init];
    _selectedIndexPathArr = [NSMutableArray array];
    self.view.backgroundColor = [UIColor colorWithRed:239/255.0 green:239/255.0 blue:244/255.0 alpha:1];
//    [self handleData];
    [self createTableViews];
    priceNumber = 0.0;
    
    
    [_shoppingCarTableView registerClass:[BWYShoppingCarTableViewCell class] forCellReuseIdentifier:@"BWYShoppingCarTableViewCell"];
}
- (void)fullMoneySendButtonMethod {
    NSString * moneyStr = moneyLable.text;
    NSArray * array = [moneyStr componentsSeparatedByString:@"合计:"];
    if (array.count == 2 && [[array objectAtIndex:1] floatValue] < _fillPrice.doubleValue
        ) {
        [balanceButton setBackgroundColor:[UIColor lightGrayColor]];
        balanceButton.enabled = NO;
    }else {
        
        [balanceButton setBackgroundColor:XNColor(236, 152, 18, 1)];
        balanceButton.enabled = YES;
    }
}
#pragma mark - VC将要出现
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    /**判断是否登录
     */
    NSUserDefaults * userLogon = [NSUserDefaults standardUserDefaults];
    NSString * isSignin_String = [userLogon objectForKey:LOGIN_STATUS];
    NSLog(@"等没等。。。%@",isSignin_String);
    if ([isSignin_String isEqualToString:@"未登录"]) {
        _viewBa = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        _viewBa.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_viewBa];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您还没有登录,请先登录后再执行操作!" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"前去登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [alert dismissViewControllerAnimated:YES completion:nil];
            WelcomViewController *welcomeVC = [[WelcomViewController alloc]init];
            UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:welcomeVC];
            [UIApplication sharedApplication].keyWindow.rootViewController = nav;
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [alert dismissViewControllerAnimated:YES completion:nil];
            //获取Main.storyboard中的首页
            UIStoryboard *mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            UITabBarController *tabBar = [mainStory instantiateViewControllerWithIdentifier:@"tabBarId"];
            self.view.window.rootViewController = tabBar;
            
        }]];
        [self presentViewController:alert animated:YES completion:nil];
        
    }else if([isSignin_String isEqualToString:@"已登录"]){
        [_viewBa removeFromSuperview];
        [self handleData];
        [self fullMoneySendButtonMethod];
        allButton.selected = YES;
        [_shoppingCarTableView reloadData];
        [_selectedIndexPathArr removeAllObjects];
        [_shoppingCarDataArray removeAllObjects];
        
        self.tabBarController.tabBar.hidden = NO;
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"合计:%0.2f元",priceNumber]];
        
        [attributedString addAttribute:NSForegroundColorAttributeName value:XNColor(236, 152, 18, 1) range:NSMakeRange(3, attributedString.length - 3)];
        [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:25] range:NSMakeRange(3, attributedString.length - 4)];
        moneyLable.attributedText = attributedString;
        //    [self CartRedPoint];
        [_shoppingCarTableView reloadData];
    }
}
#pragma mark - 获取购物车数据处理
- (void)handleData {
    if (GETShopId) {
        NSDictionary *pram = @{@"ShouJiHao":GETPHONE, @"Token":GETTOKEN, @"Duuid":GETUUID,@"ShopId":GETShopId};
        NSLog(@"%@",pram);
        [CQNetWorkTools POSTWithURL:ShopCartGetProducts par:@{@"ShouJiHao":GETPHONE, @"Token":GETTOKEN, @"Duuid":GETUUID,@"ShopId":GETShopId} success:^(id responseObject) {
            
            
            if ([[responseObject objectForKey:@"Err"] intValue]) {
                
            }else{
               
                [_shoppingCarDataArray removeAllObjects];
                NSLog(@"%@",responseObject);
                NSArray *ProArr = [responseObject objectForKey:@"Products"];
                _fillPrice =  [responseObject objectForKey:@"QiSongJia"];
                NSLog(@"%@",_fillPrice);
                  sendMoney.text = [NSString stringWithFormat:@"满%@配送",_fillPrice];
                for (NSDictionary *dic in ProArr) {
                    BWYShoppingCarModel * model = [BWYShoppingCarModel mj_objectWithKeyValues:dic];
                    model.isSelected = YES;
                    [_shoppingCarDataArray addObject:model];
                    [self.selectedIndexPathArr addObject:model];
                }
                [self numerationPrice];
                
                [_shoppingCarTableView reloadData];
                [self isArrayCountEqualZero];
            }
            
            
            
            
        } filed:^(NSError *error) {
            
        }];
    }else {
        [self isArrayCountEqualZero];
        //            [self CartRedPoint];
    }
}
#pragma mark - 购物车为0的显示
- (void)isArrayCountEqualZero
{
    if (_shoppingCarDataArray.count == 0) {
        _shoppingCarTableView.hidden = YES;
        _backGrundImageView.hidden = NO;
        [balanceButton setBackgroundColor:[UIColor lightGrayColor]];
        //购物车内没有商品时结算按钮不能点击
        balanceButton.enabled = NO;
        //全选按钮也不可点
        allButton.enabled = NO;
    }else
    {
        _shoppingCarTableView.hidden = NO;
        _backGrundImageView.hidden = YES;
        [self fullMoneySendButtonMethod];
        
        allButton.enabled = YES;
    }
}
#pragma mark - 创建视图
- (void)createTableViews
{
    _shoppingCarTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 163)];
    _shoppingCarTableView.delegate = self;
    _shoppingCarTableView.dataSource = self;
    [self.view addSubview:_shoppingCarTableView];
    //在数据很少的时候 避免显示多余的分割线
    UIView *v = [[UIView alloc] initWithFrame:CGRectZero];
    [_shoppingCarTableView setTableFooterView:v];
    UIView *settleToolView = [[UIView alloc]initWithFrame:CGRectMake(0, XNWindowHeight -163, XNWindowWidth, 50)];
    settleToolView.layer.borderWidth = 1;
    //边框宽度
    CGColorSpaceRef colorSpaces = CGColorSpaceCreateDeviceRGB();
    CGColorRef toolColor = CGColorCreate(colorSpaces,(CGFloat[]){ 231/255.f, 231/255.f, 231/255.f, 1 });
    
    [settleToolView.layer setBorderColor:toolColor];//边框颜色
    settleToolView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:settleToolView];
    
    sendMoney = [[UILabel alloc] init];
    sendMoney.frame = CGRectMake(XNWindowWidth/1.9, XNWindowHeight-150, XNWindowWidth/3.5, 30);
   
    [self.view addSubview:sendMoney];
    //全选按钮
    allButton = [UIButton buttonWithType:UIButtonTypeCustom];
    allButton.frame = CGRectMake(10, XNWindowHeight-145, 30, 30);
    [allButton setImage:[UIImage imageNamed:@"对号正常.png"] forState:UIControlStateNormal];
    [allButton setImage:[UIImage imageNamed:@"对号选中.png"] forState:UIControlStateSelected];
    allButton.titleLabel.font = [UIFont systemFontOfSize:14];
    allButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [allButton addTarget:self action:@selector(allButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    allButton.selected = NO;
    [self.view addSubview:allButton];
    
    UILabel * quanxuanLable = [[UILabel alloc]initWithFrame:CGRectMake(allButton.frame.origin.x + 28, allButton.frame.origin.y - 3, 30, 30)];
    quanxuanLable.text = @"";
    quanxuanLable.font = [UIFont systemFontOfSize:14];
    quanxuanLable.textAlignment = NSTextAlignmentLeft;
    [self.view addSubview:quanxuanLable];
    
    moneyLable = [[UILabel alloc]initWithFrame:CGRectMake(allButton.frame.origin.x+10, allButton.frame.origin.y - 3, 160, 25)];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"合计:%0.2f元",priceNumber]];
    
    [attributedString addAttribute:NSForegroundColorAttributeName value:XNColor(236, 152, 18, 1) range:NSMakeRange(3, attributedString.length - 3)];
    [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:25] range:NSMakeRange(3, attributedString.length - 4)];
    moneyLable.attributedText = attributedString;
    moneyLable.font = [UIFont systemFontOfSize:17];
    moneyLable.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:moneyLable];
    
    //结算按钮
    balanceButton = [UIButton buttonWithType:UIButtonTypeSystem];
    balanceButton.frame = CGRectMake(self.view.frame.size.width - XNWindowWidth /4.5, self.view.frame.size.height - 163, XNWindowWidth /4.5, 50);
    //    balanceButton.backgroundColor = XNColor(236, 152, 18, 1);
    [balanceButton setTitle:@"结算" forState:UIControlStateNormal];
    [balanceButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [balanceButton setTitleColor:[UIColor whiteColor] forState:UIControlStateDisabled];
    //    [balanceButton.layer setBorderWidth:1.3]; //边框宽度
    //    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    //    CGColorRef colorref = CGColorCreate(colorSpace,(CGFloat[]){ 236/255.f, 152/255.f, 18/255.f, 1 });
    //
    //    [balanceButton.layer setBorderColor:colorref];//边框颜色
    [balanceButton addTarget:self action:@selector(balanceButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:balanceButton];
    
    _backGrundImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, XNWindowWidth, XNWindowHeight -49-64)];
    _backGrundImageView.image = [UIImage imageNamed:@"空购物车"];
    _backGrundImageView.hidden = YES;
    [self.view addSubview:_backGrundImageView];
    
}
#pragma mark - 购物车结算按钮
- (void)balanceButtonClick:(UIButton *)button
{
    //    ConfirmOderViewController *oder = [[ConfirmOderViewController alloc] init];
    //    oder.confirmArr = self.selectedIndexPathArr;
    //    [self.navigationController pushViewController: oder animated:YES];
    NSString * moneyStr = moneyLable.text;
    NSArray * array = [moneyStr componentsSeparatedByString:@"合计:"];
    if (array.count == 2 && [[array objectAtIndex:1] floatValue] < 20.0
        ) {
        [balanceButton setBackgroundColor:[UIColor lightGrayColor]];
        balanceButton.enabled = NO;
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请选择商品" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:action1];
        [self presentViewController:alert animated:YES completion:^{
            
        }];
    }else
    {
        [balanceButton setBackgroundColor:XNColor(236, 152, 18, 1)];
        balanceButton.enabled = YES;
        ConfirmOderViewController *oder = [[ConfirmOderViewController alloc] init];
        oder.confirmArr = self.selectedIndexPathArr;
        [self.navigationController pushViewController: oder animated:YES];
    }
    
    
}
#pragma mark - 头部视图行高
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 42;
}
#pragma mark - 分区头部视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    _header =  [[SectionHeaderTableView alloc] initWithFrame:CGRectMake(0, 0, XNWindowWidth, 40)];
    BWYShoppingCarModel * model =[_shoppingCarDataArray firstObject];
    _header.shopName.text = model.ShopName;
    return _header;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return _shoppingCarDataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120;
}
#pragma mark - 什么样的cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BWYShoppingCarTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"BWYShoppingCarTableViewCell"];
    if (!cell) {
        cell = [[BWYShoppingCarTableViewCell alloc]initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:@"BWYShoppingCarTableViewCell"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (_shoppingCarDataArray.count > 0) {
        BWYShoppingCarModel * model = [_shoppingCarDataArray objectAtIndex:indexPath.row];
        cell.delegate = self;
        
        [cell customDataWithModel:model];
    }
    return cell;
}
#pragma mark - 打印选中了哪一行
- (void)isSelect:(UITableViewCell *)cell andModel:(BWYShoppingCarModel *)model
{
    NSIndexPath * indexPath = [_shoppingCarTableView indexPathForCell:cell];
    [self numerationPrice];
    if (model.isSelected == NO) {
        allButton.selected = NO;
        
        [self.selectedIndexPathArr removeObject:[_shoppingCarDataArray objectAtIndex:indexPath.row]];
    }else {
        
        [self.selectedIndexPathArr addObject:[_shoppingCarDataArray objectAtIndex:indexPath.row]];
    }
    int x = 0;
    for (BWYShoppingCarModel *models in _shoppingCarDataArray) {
        if (models.isSelected == NO) {
            x++;
        }
    }
    if (x == 0) {
        allButton.selected = YES;
    }
    [_shoppingCarTableView reloadData];
    DLog(@"第%ld行是否选中%d",(long)indexPath.row,model.isSelected);
}
#pragma mark - 删除按钮点击代理
- (void)isDelet:(UITableViewCell *)cell andDeletButtonTag:(NSInteger)deletTag
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"删除提示" message:@"确认要删除该商品吗?" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSIndexPath * indexPath = [_shoppingCarTableView indexPathForCell:cell];
        
        BWYShoppingCarModel * model = [_shoppingCarDataArray objectAtIndex:indexPath.row];
        [_shoppingCarDataArray removeObjectAtIndex:indexPath.row];
        
        [CQNetWorkTools POSTWithURL:PostRemoveFromCart par:@{@"ShouJiHao":GETPHONE,@"Token":GETTOKEN,@"Duuid":GETUUID,@"ProductID":[NSString stringWithFormat:@"%.0f", model.Id]} success:^(id responseObject) {
            [MyProductsTool deleteOneProductsFromSQL:model.Id];
        } filed:^(NSError *error) {
            DLog(@"%@", error);
        }];
        [_shoppingCarTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
        [self isArrayCountEqualZero];
        //重新计算价格
        [self numerationPrice];
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:action1];
    [alert addAction:action2];
    [self presentViewController:alert animated:YES completion:^{
        
    }];
    
    
}
- (void)didEnterBackground:(NSNotification *)notification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
    [self.presentedViewController dismissViewControllerAnimated:NO completion:nil];
}
//- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex;

- (void)CartRedPoint {
    if (GETShopId) {
        [CQNetWorkTools POSTWithURL:ShopCartGetProducts par:@{@"ShouJiHao":GETPHONE,@"Token":GETTOKEN, @"Duuid":GETUUID,@"ShopId":GETShopId} success:^(id responseObject) {
            
            self.navigationController.tabBarController.viewControllers[2].tabBarItem.badgeValue = [NSString stringWithFormat:@"%@", [responseObject objectForKey:@"TotalCount"]];
            if ([[NSString stringWithFormat:@"%@", [responseObject objectForKey:@"TotalCount"]] isEqualToString:@"0"]) {
                self.navigationController.tabBarController.viewControllers[2].tabBarItem.badgeValue = nil;
            }
        } filed:^(NSError *error) {
            DLog(@"%@", error);
        }];
    }else {
        self.navigationController.tabBarController.viewControllers[2].tabBarItem.badgeValue = nil;
    }
}
#pragma mark - 增加 减少按钮点击代理
- (void)goodsCount:(UITableViewCell *)cell andButtonTag:(NSInteger)AddOrSubTag {
    [self fullMoneySendButtonMethod];
    NSIndexPath * indexPath = [_shoppingCarTableView indexPathForCell:cell];
    switch (AddOrSubTag) {
        case 105:
        {
            BWYShoppingCarModel * model = [_shoppingCarDataArray objectAtIndex:indexPath.row];
            if (model.Count > 1) {
                model.Count--;
                
                [CQNetWorkTools POSTWithURL:PostOperationShoppingCar par:@{@"ShouJiHao":GETPHONE,@"Token":GETTOKEN,@"Duuid":GETUUID,@"ProductID":[NSString stringWithFormat:@"%.0f", model.Id],@"Count":[NSString stringWithFormat:@"%ld", (long)model.Count]} success:^(id responseObject) {
                    [MyProductsTool ClickJiaJianProduct:model.Id andCount:model.Count blockcompletion:^(BOOL updata) {
                        DLog(@"--");
                    }];
                    //                    [self CartRedPoint];
                    
                    
                } filed:^(NSError *error) {
                    DLog(@"减少购物车商品失败%@", error);
                }];
            }
            break;
        }
        case 106:
        {
            BWYShoppingCarModel * model = [_shoppingCarDataArray objectAtIndex:indexPath.row];
            if (model.Count < model.Sku) {
                model.Count++;
                [CQNetWorkTools POSTWithURL:PostOperationShoppingCar par:@{@"ShouJiHao":GETPHONE,@"Token":GETTOKEN,@"Duuid":GETUUID,@"ProductID":[NSString stringWithFormat:@"%.0f", model.Id],@"Count":[NSString stringWithFormat:@"%ld", (long)model.Count]} success:^(id responseObject) {                                                  [MyProductsTool ClickJiaJianProduct:model.Id andCount:model.Count blockcompletion:^(BOOL updata) {
                    DLog(@"++");
                }];
                    
                    
                    //                    [self CartRedPoint];
                    
                } filed:^(NSError *error) {
                    DLog(@"增加购物车商品失败%@", error);
                }]; }else {
                    [SVProgressHUD  showWithStatus:@"库存不足"];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [SVProgressHUD dismiss];
                    });};
            
            
            break;
        }
        default:
            break;
    }
    //重新计算价格
    [self numerationPrice];
    [_shoppingCarTableView reloadData];
}

//全选按钮点击
- (void)allButtonClick:(UIButton *)button
{
    button.selected = !button.selected;
    for (int i = 0; i < _shoppingCarDataArray.count; i++) {
        BWYShoppingCarModel * model = [_shoppingCarDataArray objectAtIndex:i];
        model.isSelected = button.selected;
    }
    if (allButton.isSelected == NO) {
        [self.selectedIndexPathArr removeAllObjects];
    }
    //重新计算价格
    [self numerationPrice];
    [_shoppingCarTableView reloadData];
}

//计算总价
- (void)numerationPrice
{
    for (int i = 0; i < _shoppingCarDataArray.count; i++) {
        BWYShoppingCarModel * model = [_shoppingCarDataArray objectAtIndex:i];
        if (model.isSelected) {
            priceNumber = priceNumber + model.Count * [model.Price floatValue];
        }
    }
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"合计:%0.2f元",priceNumber]];
    
    [attributedString addAttribute:NSForegroundColorAttributeName value:XNColor(236, 152, 18, 1) range:NSMakeRange(3, attributedString.length - 3)];
    [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:25] range:NSMakeRange(3, attributedString.length - 4)];
    moneyLable.attributedText = attributedString;
    //    moneyLable.text = [NSString stringWithFormat:@"合计:%0.2f元",priceNumber];
    
    priceNumber = 0.0;
    [self fullMoneySendButtonMethod];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
